package edu.mju.controller;

import com.alibaba.fastjson.JSONObject;
import edu.mju.entity.TouristCompany;
import edu.mju.entity.User;
import edu.mju.service.ICompanyService;
import edu.mju.service.IUserService;
import edu.mju.service.impl.CompanyServiceImpl;
import edu.mju.service.impl.UserServiceImpl;
import edu.mju.util.Pager;
import edu.mju.util.RequestStrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author:wyp
 * @Date:2020/5/24 21:40
 */
@WebServlet("/companyControl")
public class CompanyController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一编码，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charSet=utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        //获取method
        String method = req.getParameter("method");

        System.out.println("doget:"+method);
        if("routesAdd".equals(method)){
            //对应company的routes-list.jsp的添加线路按钮
            req.getRequestDispatcher("/WEB-INF/view/company/routes-add.jsp").forward(req,resp);
        }else if("companyList".equals(method)){
            //对应backindex.jsp的 旅游公司列表
            req.getRequestDispatcher("/WEB-INF/view/backindex/company-list.jsp").forward(req,resp);
        }else if("companyAdd".equals(method)){
            //对应company-list.jsp的添加公司按钮
            req.getRequestDispatcher("/WEB-INF/view/backindex/company-add.jsp").forward(req,resp);
        }else if("companyFind".equals(method)){
            //对应company-list.jsp的编辑按钮
            String companyId = req.getParameter("companyId");
            req.getRequestDispatcher("/WEB-INF/view/backindex/company-edit.jsp?companyId="+companyId).forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一编码
        resp.setContentType("text/html;charSet=utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        //获取method

        String method = req.getParameter("method");
        System.out.println("dopost:"+method);
        if("companyList".equals(method)){
            //对应company-list.jsp的请求
            pagernate(req, resp);
        }else if("companyAdd".equals(method)){
            //对应company-add.jsp 的companyAdd提交按钮
            companyAdd(req,resp);
        }else if("companyFind".equals(method)){
            //对应company-edit.jsp 的页面载入ajax
            companyFind(req,resp);
        }else if("companyEdit".equals(method)){
            //对应company-edit.jsp 的页面更改公司名
            companyEdit(req,resp);
        }else if("companyDelete".equals(method)){
            //对应company-list.jsp 的页面删除公司
            companyDelete(req,resp);
        }
    }


    /**
     *  删除公司
     * @param req
     * @param resp
     */
    private void companyDelete(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Integer companyId = RequestStrUtil.getValue(req.getParameter("companyId"),0);
            ICompanyService companyService = new CompanyServiceImpl();
            boolean delRoutes = companyService.delete(companyId);
            if(delRoutes) {
                //删除用户
                Integer userId = RequestStrUtil.getValue(req.getParameter("userId"),0);
                IUserService userService = new UserServiceImpl();
                userService.delete(userId);

                String result = JSONObject.toJSONString(delRoutes);
                System.out.println(result);
                resp.getWriter().write(result);
            }else {
                //只要返回的不是json格式，ajax执行error
                resp.getWriter().write("删除失败！");
            }

        }catch (Exception e){
            System.out.println("routesDel方法捕获异常");
            e.printStackTrace();
        }
    }

    /**
     *  更改公司名称
     * @param req
     * @param resp
     */
    private void companyEdit(HttpServletRequest req, HttpServletResponse resp){
        try {
            //获取ajax提交的参数 ，对应company-add.jsp的参数
            Integer companyId = RequestStrUtil.getValue(req.getParameter("companyId"),0) ;
            String companyName = req.getParameter("companyName");

            //将获取的公司信息以及注册的用户ID传入touristCompany对象
            TouristCompany touristCompany = new TouristCompany();
            touristCompany.setCompanyId(Integer.valueOf(companyId));
            touristCompany.setCompanyName(companyName);

            //执行查询Company操作
            ICompanyService companyService = new CompanyServiceImpl();
            companyService.save(touristCompany);

            //返回浏览器json格式的结果

            String result = JSONObject.toJSONString(touristCompany);
            System.out.println(result);
            resp.getWriter().write(result);


        }catch (Exception e){
            System.out.println("companyAdd方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     *  获取公司信息
     * @param req
     * @param resp
     */
    private void companyFind(HttpServletRequest req, HttpServletResponse resp){
        try {
            //获取ajax提交的参数 ，对应company-add.jsp的参数
            Integer companyId =RequestStrUtil.getValue(req.getParameter("companyId"),0) ;

            //将获取的公司信息以及注册的用户ID传入touristCompany对象
            TouristCompany touristCompany = new TouristCompany();
            touristCompany.setCompanyId(companyId);

            //执行查询Company操作
            ICompanyService companyService = new CompanyServiceImpl();
            touristCompany = companyService.findBycompanyId(touristCompany.getCompanyId());

            //返回浏览器json格式的结果

            String result = JSONObject.toJSONString(touristCompany);
            System.out.println(result);
            resp.getWriter().write(result);


        }catch (Exception e){
            System.out.println("companyAdd方法跳转失败：");
            e.printStackTrace();
        }
    }


    /**
     *  添加公司
     * @param req
     * @param resp
     */
    private void companyAdd(HttpServletRequest req, HttpServletResponse resp){
        try {
            //获取ajax提交的参数 ，对应company-add.jsp的参数
            String companyName = req.getParameter("companyName");
            String userName = req.getParameter("userName");
            String userPassword = req.getParameter("userPassword");
            String userTel = req.getParameter("userTel");

            //将获取的用户信息传入user对象
            User user = new User();
            user.setUserName(userName);
            user.setUserPassword(userPassword);
            user.setUserTel(userTel);

            //执行注册用户操作
            IUserService userService =new UserServiceImpl();
            user = userService.registerCompanyUser(user);

            //将获取的公司信息以及注册的用户ID传入touristCompany对象
            TouristCompany touristCompany = new TouristCompany();
            touristCompany.setCompanyName(companyName);
            touristCompany.setUserId(user.getUserId());

            //执行注册touristCompany操作
            ICompanyService companyService = new CompanyServiceImpl();
            boolean Isinsert = companyService.save(touristCompany);

            //返回浏览器json格式的结果
            if(Isinsert) {
                String result = JSONObject.toJSONString(Isinsert);
                System.out.println(result);
                resp.getWriter().write(result);
            }else {
                //只要返回的不是json格式，ajax执行error
                resp.getWriter().write("添加失败！");
            }

        }catch (Exception e){
            System.out.println("companyAdd方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     * 分页查询
     * @param req
     * @param resp
     */
    public void pagernate(HttpServletRequest req, HttpServletResponse resp){

        //每页显示数据
        int pageSize = 5 ;
        //设定默认当前页码数
        int page = 1;

        TouristCompany company = new TouristCompany();
        String getcompanyName = req.getParameter("companyName");
        Integer getcompanyId =RequestStrUtil.getValue(req.getParameter("companyId"),0);
        company.setCompanyId(getcompanyId);
        String getPage = req.getParameter("page");
        if(getPage !=null && ! "".equals(getPage)){
            page = (Integer.valueOf(getPage)) ;
        }
        company.setCompanyName(getcompanyName);
        ICompanyService companyService = new CompanyServiceImpl();
        Pager pager = companyService.pagernate(page,pageSize,company);
        req.getSession().setAttribute("pager",pager);

        String result = JSONObject.toJSONString(pager);
        System.out.println("pagernate的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }
}
